import Vue from 'vue'
import promise from 'es6-promise'
import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'

promise.polyfill() // require('es6-promise').polyfill()

const service = axios.create({
  baseURL: '',
  timeout: 10000,
  responseType: 'json',
  withCredentials: false, // cookie 表示跨域请求时是否需要使用凭证
  headers: {
    // application/json;charset=utf-8
    // 'Access-Token': 'usertoken'
  }
})

// service.defaults.baseURL = '' //默认域名
service.interceptors.request.use(
  config => {
    const token = vm.$store.getters.getToken
    !config.data && (config.data = {}) // 设置默认 data
    token && (config.data.token = token)
    if (!config.headers['Content-Type']) { // 设置默认响应头
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.data = qs.stringify(config.data)
    }
    // config.method === 'OPTIONS'
    return config
  },
  error => {
    Message({
      showClose: true,
      message: error,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    /* // IE 9
    if (response.data == null && response.config.responseType === 'JSON' && response.request.responseText != null) {
      try {
        response.data = JSON.parse(response.request.responseText);
      } catch (e) {
      }
    }
    return response; */
    const info = qs.parse(response.config.data)

    if (response.status === 200) {
      const data = response.data || JSON.parse(response.request.responseText)
      const code = data.code
      let res
      switch (code) {
        case 0:
          res = data
          return data
        case 1:
          res = data
          info.noMessage ||
          (
            Message({
              showClose: true,
              message: data.msg,
              type: 'error'
            })
          )
          return data
        default:
          res = data
      }
      res = data
      return Promise.reject(res)
      // return res
      // return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        case 500:
          Message({
            showClose: true,
            message: '服务器修复中...',
            type: 'error'
          })
          break
        // 404请求不存在
        case 404:
          Message({
            showClose: true,
            message: '网络请求不存在',
            type: 'error'
          })
          break
        // 其他错误，直接抛出错误提示
        default:
          Message({
            showClose: true,
            message: error.response.data.message,
            type: 'error'
          })
      }
      return Promise.reject(error.response)
    }
  }
)

Vue.prototype.$http = service

export default service

